package com.ansion.preference;

import android.content.Context;
import android.content.SharedPreferences;

import com.ansion.utils.ResourceUtils;

import java.util.Map;
import java.util.Set;

public class SharePreference implements ITurboBasePreference {

    private Context mContext;
    private SharedPreferences mDefaultPreferences;

    public SharePreference(String key) {
        mContext = ResourceUtils.getContext();
        mDefaultPreferences = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    }

    public boolean putFloat(String key, float value) {
        boolean flag = mDefaultPreferences.edit().putFloat(key, value)
                .commit();
        return flag;
    }

    public float getFloat(String key, float defValue) {
        return mDefaultPreferences.getFloat(key, defValue);
    }

    public boolean putInt(String key, int value) {
        boolean flag = mDefaultPreferences.edit().putInt(key, value)
                .commit();
        return flag;
    }

    public int getInt(String key, int defValue) {
        return mDefaultPreferences.getInt(key, defValue);
    }

    public boolean putLong(String key, long value) {
        boolean flag = mDefaultPreferences.edit().putLong(key, value)
                .commit();
        return flag;
    }

    public long getLong(String key, long defValue) {
        return mDefaultPreferences.getLong(key, defValue);
    }

    public boolean putString(String key, String value) {
        boolean flag = mDefaultPreferences.edit().putString(key, value)
                .commit();
        return flag;
    }

    public String getString(String key, String defValue) {
        return mDefaultPreferences.getString(key, defValue);
    }

    public boolean putBoolean(String key, boolean value) {
        boolean flag = mDefaultPreferences.edit().putBoolean(key, value)
                .commit();
        return flag;
    }

    public boolean getBoolean(String key, boolean defValue) {
        return mDefaultPreferences.getBoolean(key, defValue);
    }

    @Override
    public boolean contains(String key) {
        return mDefaultPreferences.contains(key);
    }

    @Override
    public void remove(String key) {
        mDefaultPreferences.edit().remove(key).apply();
    }

    @Override
    public String[] getAllKeys() {
        Map<String, ?> map = mDefaultPreferences.getAll();
        if(map == null || map.size() <= 0) {
            return new String[0];
        }

        Set<String> set = map.keySet();
        String[] s = new String[set.size()];
        return set.toArray(s);
    }

    @Override
    public SharedPreferences.Editor getEditor() {
        return mDefaultPreferences.edit();
    }

    @Override
    public void clear() {
        mDefaultPreferences.edit().clear().apply();
    }
}
